﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Service
{
    /// <summary>
    /// 广播接收的数据
    /// </summary>
    [StructLayout(LayoutKind.Sequential, Pack = 1)]
    public struct UdpBroadcastItem
    {

        public UdpBroadcastItem(UdpBroadcastFlag flag)
        {
            this = default(UdpBroadcastItem);
            this.Flag = flag;
            this.Data = new byte[512];
        }


        /// <summary>
        /// 获取广播中的数据字符串
        /// </summary>
        /// <returns></returns>
        public string GetString()
        {
            return Encoding.Unicode.GetString(this.Data).TrimEnd(new char[1]);
        }


        /// <summary>
        /// 保存广播数据
        /// </summary>
        /// <param name="value"></param>
        public void SetData(string value)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(value);
            int length = (bytes.Length > this.Data.Length) ? this.Data.Length : bytes.Length;
            Array.Clear(this.Data, 0, this.Data.Length);
            Array.Copy(bytes, this.Data, length);
        }


        /// <summary>
        /// 广播标志位
        /// </summary>
        public UdpBroadcastFlag Flag;


        /// <summary>
        /// 广播数据
        /// </summary>
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 512)]
        public byte[] Data;


    }
}
